package com.algorithm.Map;


import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;

/**
 * 何时选择Tree Map
 * 当元素具备可比较性要求升序遍历的时候可以选择TreeMap
 */
public class TreeMap<K,V> implements Map<K,V>{
    private static final boolean RED = true;
    private static final boolean BLACK = false;
    private int size;
    private Node<K,V> root;
    private Comparator comparator;

    public TreeMap(Comparator comparator) {
        this.comparator = comparator;
    }

    public TreeMap() {
        this(null);
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        root = null;
        size = 0;
    }

    @Override
    public V put(K key, V value) {
        keyNotNullCheck(key);
        if (root == null) {
            root = createNode(key,value,null);;
            size++;
            afterAdd(root);
            return null;
        }

        Node<K,V> node = root;
        Node<K,V> parent;
        int cmp;
        do {
            cmp = compare(key,node.key);
            parent = node;
            if (cmp > 0) {
                node = node.right;
            }else if (cmp < 0) {
                node = node.left;
            }else {
                node.key = key;
                V oldValue = node.value;
                node.value = value;
                return oldValue;
            }
        }while (node != null);

        Node<K,V> newNode = createNode(key,value,parent);
        if (cmp > 0) {
            parent.right = newNode;
        }else {
            parent.left = newNode;
        }
        afterAdd(newNode);
        size++;
        return null;
    }

    private void afterAdd(Node<K,V> node) {
        Node<K,V> parent = node.parent;
        if (parent == null) {
            black(node);
            return;
        }

        if (isBlack(parent)) return;

        Node<K,V> uncle = parent.sibling();
        Node<K,V> grand = red(parent.parent);
        if (isRed(uncle)) {//r-b-r 需要溢出
            black(parent);
            black(uncle);
            afterAdd(grand);
            return;
        }

        if (parent.isLeftChild()) {
            if (node.isLeftChild()) {
                black(parent);
            }else {
                black(node);
                rotatedLeft(parent);
            }
            rotatedRight(grand);
        }else {
            if (node.isLeftChild()) {
                black(node);
                rotatedRight(parent);
            }else {
                black(parent);
            }
            rotatedLeft(grand);
        }
    }

    /**
     * remove element
     */
    @Override
    public V remove(K key) {
        return remove(node(key));
    }

    public V remove(Node<K,V> node) {
        if (node == null) return null;
        V oldValue = node.value;

        if (node.hasTwoChild()) {
            Node<K,V> pre = successor(node);
            node.key = pre.key;
            node.value = pre.value;
            node = pre;
        }

        Node<K,V> replaceNode = node.left != null ? node.left : node.right;
        if (replaceNode != null) {
            replaceNode.parent = node.parent;
            if (node.parent == null) {
                root = replaceNode;
            }else if (node.isLeftChild()) {
                node.parent.left = replaceNode;
            }else {
                node.parent.right = replaceNode;
            }
            afterRemove(replaceNode);
        }else if (node.parent == null) {
            root = null;
        }else {
            if (node.isLeftChild()) {
                node.parent.left = null;
            }else {
                node.parent.right = null;
            }
            afterRemove(node);
        }
        size--;
        return oldValue;
    }

    /**
     * r-b-r r-b b-r b
     */
    protected void afterRemove(Node<K,V> node) {
        if (isRed(node)) {
            black(node);
            return;
        }

        Node<K,V> parent = node.parent;
        if (parent == null) return;

        boolean left = parent.left == null || node.isLeftChild();
        Node<K,V> sibling = left ? parent.right : parent.left;
        if (left) {
            if (isRed(sibling)) {
                red(parent);
                black(sibling);
                rotatedLeft(parent);
                sibling = parent.right;
            }

            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean bNeedRet = isBlack(parent);
                red(sibling);
                black(parent);
                if (bNeedRet) {
                    afterRemove(parent);
                }
            }else {
                if (isBlack(sibling.right)) {
                    rotatedRight(sibling);
                    sibling = parent.right;
                }
                color(sibling,colorOf(parent));
                black(parent);
                black(sibling.right);
                rotatedLeft(parent);
            }
        }else {
            if (isRed(sibling)) {
                red(parent);
                black(sibling);
                rotatedRight(parent);
                sibling = parent.left;
            }

            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean bNeedRet = isBlack(parent);
                red(sibling);
                black(parent);
                if (bNeedRet) {
                    afterRemove(parent);
                }
            }else {
                if (isBlack(sibling.left)) {
                    rotatedLeft(sibling);
                    sibling = parent.left;
                }
                color(sibling,colorOf(parent));
                black(parent);
                black(sibling.left);
                rotatedRight(parent);
            }
        }
    }

    @Override
    public V get(K key) {
        keyNotNullCheck(key);
        Node<K, V> node = node(key);
        return node != null ? node.value : null;
    }

    @Override
    public boolean containsKey(K key) {
        return node(key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        if (root == null) return false;
        Queue<Node<K,V>> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            Node<K,V> node = queue.poll();
            if (valueEquals(value,node.value)) return true;
            if (node.left != null) {
                queue.offer(node.left);
            }

            if (node.right != null) {
                queue.offer(node.right);
            }
        }
        return false;
    }

    @Override
    public void traversal(Visitor<K, V> visitor) {
        if (visitor == null) return;
        traversal(root, visitor);
    }

    private void traversal(Node<K, V> node, Visitor<K, V> visitor) {
        if (node == null || visitor.stop) return;

        traversal(node.left, visitor);
        if (visitor.stop) return;
        visitor.visit(node.key, node.value);
        traversal(node.right, visitor);
    }



    private boolean valueEquals(V v1,V v2) {
        return v1 == null ? v2 == null : v1.equals(v2);
    }


    private Node<K,V> successor(Node<K,V> node) {
        if (node == null) return null;
        Node<K,V> p = node.right;
        if (p != null){
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }

        while (node.parent != null && node.parent.right == node) {
            node = node.parent;
        }
        return node.parent;
    }

    private Node<K,V> node(K key) {
        Node<K,V> node = root;
        if (node == null) return null;
        do {
            int cmp = compare(key,node.key);
            if (cmp == 0) return node;
            if (cmp > 0) {
                node = node.right;
            }else {
                node = node.left;
            }
        }while (node != null);
        return null;
    }

    private int compare(K key1,K key2) {
        if (comparator != null) {
            return comparator.compare(key1,key2);
        }
        return ((Comparable) key1).compareTo(key2);
    }

    private Node<K,V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<>(key,value,parent);
    }

    private void keyNotNullCheck(K key) {
        if (key == null) {
            throw new IllegalArgumentException("key is must not null");
        }
    }

    private boolean colorOf(Node<K,V> node) {
        return node == null ? BLACK : node.color;
    }

    private boolean isRed(Node<K,V> node) {
        return colorOf(node) == RED;
    }

    private boolean isBlack(Node<K,V> node) {
        return colorOf(node) == BLACK;
    }

    private Node<K,V> color(Node<K,V> node,boolean color) {
        if (node == null) return null;
        node.color = color;
        return node;
    }

    private Node<K,V> red(Node<K,V> node) {
        return color(node, RED);
    }

    private Node<K,V> black(Node<K,V> node) {
        return color(node,BLACK);
    }

    private void rotatedLeft(Node<K,V> grand) {
        Node<K,V> parent = grand.right;
        Node<K,V> child = parent.left;

        grand.right = child;
        parent.left = grand;
        afterRotated(grand,parent,child);
    }

    private void rotatedRight(Node<K,V> grand) {
        Node<K,V> parent = grand.left;
        Node<K,V> child = parent.right;

        grand.left = child;
        parent.right = grand;
        afterRotated(grand,parent,child);
    }

    private void afterRotated(Node<K,V> grand,Node<K,V> parent,Node<K,V> child) {
        parent.parent = grand.parent;
        if (grand.isLeftChild()) {
            parent.parent.left = parent;
        }else if (grand.isRightChild()) {
            parent.parent.right = parent;
        }else {
            root = parent;
        }

        if (child != null) {
            child.parent = grand;
        }
        grand.parent = parent;
    }

    private static class Node<K,V> {
        K key;
        V value;
        boolean color = RED;
        Node<K,V> left;
        Node<K,V> right;
        Node<K,V> parent;

        Node(K key, V value, Node<K, V> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        boolean hasTwoChild() {
            return left != null && right != null;
        }

        boolean isLeftChild() {
            return parent != null && parent.left == this;
        }

        boolean isRightChild() {
            return parent != null && parent.right == this;
        }

        Node<K,V> sibling() {
            if (parent == null) return null;
            if (isLeftChild()) return parent.right;
            if (isRightChild()) return parent.left;
            return null;
        }
    }
}
